package dijjer.io.xfer.http.handlers;

import java.io.ByteArrayOutputStream;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;

import dijjer.AbstractFactory;
import dijjer.io.comm.AbstractPeer;
import dijjer.io.comm.WebPeer;
import dijjer.io.store.DataStore;
import dijjer.io.xfer.http.HTTPResponse;
import dijjer.io.xfer.http.PageHandler;
import dijjer.util.GIFEncoder;
import dijjer.util.VeryLongInteger;

public class GraphGIFHandler extends PageHandler {

	public static final String VERSION = "$Id: GraphGIFHandler.java 33 2009-03-20 13:26:16Z mathias.demare $";

	public HTTPResponse handleRequest(String method, String url, Map params, Map headers, Reader in)
	{
		GIFResponse response = new GIFResponse(getGraphGif(), HttpURLConnection.HTTP_OK, "OK");
		response.addHeader("Cache-control", "no-cache");
		response.addHeader("Pragma", "no-cache");
		return response;
	}

	private GIFEncoder getGraphGif()
	{
		byte[][] red = new byte[256][1];
		byte[][] green = new byte[256][1];
		byte[][] blue = new byte[256][1];
		for (int x = 0; x < 256; x++) {
			red[x][0] = (byte) 220;
			green[x][0] = (byte) 220;
			blue[x][0] = (byte) 220;
		}
		for (Iterator i = DataStore.getDataStore().getAllKeys().iterator(); i.hasNext();) {
			VeryLongInteger vli = (VeryLongInteger) i.next();
			int ppos = vli.getMostSignificantByte();
			blue[ppos][0] = (byte) 255;
			red[ppos][0] = (byte) (220 * DataStore.getDataStore().getAgeByKey(vli));
			green[ppos][0] = (byte) (220 * DataStore.getDataStore().getAgeByKey(vli));
		}
		for (Iterator i = ((ArrayList) AbstractFactory.getFactory().getRoutingTable().getPeers().clone()).iterator(); i.hasNext();) {
			AbstractPeer p = (AbstractPeer) i.next();
			if (p == null) {
				continue;
			}
			int ppos = p.getHash().getMostSignificantByte();
			green[ppos][0] = (byte) 255;
			red[ppos][0] = (byte) 0;
			blue[ppos][0] = (byte) 0;
		}
		int ppos = AbstractFactory.getFactory().getRoutingTable().getPeer().getHash().getMostSignificantByte();
		red[ppos][0] = (byte) 255;
		green[ppos][0] = (byte) 0;
		blue[ppos][0] = (byte) 0;
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		return new GIFEncoder(red, green, blue);
	}

}
